const axios = require('axios')
const randomstring = require("randomstring")
const querystring = require('querystring')
const crypto = require('crypto')

const sign = async (ctx, next) => {
  const appId = 'wx7ba8ee8a8beace33'
  const appsecret = 'd62705bd6fdf27441397683019077e20'

  // 获取access_token
  const { data: { access_token } } = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appsecret}`)

  // 获取票据：jsapi_ticket
  const { data: { ticket } } = await axios.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`)

  // 生成签名
  //1、生成 noncestr
  const noncestr = randomstring.generate(32)
  //2、有效的 jsapi_ticket
  const jsapi_ticket = ticket
  //3、时间戳 timestamp
  const timestamp = Math.floor((new Date().getTime())/1000)
  //4、当前的URL地址
  const url = 'http://47.95.4.181/'
  //5、字典排序
  const obj = {
    timestamp,
    jsapi_ticket,
    noncestr,
    url
  }
  const orderedObj = Object.keys(obj).sort().reduce((o, key) => {
    o[key] = obj[key]
    return o
  }, {})
  //6、生成string1
  const string1 = querystring.stringify(orderedObj, null, null, { 
    encodeURIComponent: (str) => {
      return querystring.unescape(str)
    }
  })
  //7、生成signature
  const signature = crypto.createHash('sha1').update(string1).digest('hex')

  ctx.body = {
    appId, // 必填，公众号的唯一标识
    timestamp, // 必填，生成签名的时间戳
    nonceStr: noncestr, // 必填，生成签名的随机串
    signature// 必填，签名
  }
}

module.exports = {
  sign
}